<?php

namespace App\Http\Controllers\Api\V1\Requests;

use App\Models\User;
use App\Supports\Sms\Sms;

/**
 * Class SmsCodeRequest
 * @package App\Http\Controllers\Api\V1\Requests
 *
 * @property $phone
 * @property $type
 * @property $captcha_key
 * @property $captcha_code
 */
class SmsCodeRequest extends FormRequest
{
    public function rules(): array
    {
	    $type = request('type');

	    $rules = [];

	    if ($type == 'register_account') {
		    $rules = [
			    'phone' => 'required|phone:CN,mobile|unique:users',
			    'type' => 'required|string'
		    ];
        } elseif($type == 'bind_bank_card' || $type =="bind_alipay" || $type=="bind_user_pay_method"  || $type=="withdraw"){

             $rules = [
                'phone' => 'required|phone:CN,mobile',
                'type' => 'required|string'
            ];
	    } elseif ($type == 'reset_password' or $type == 'set_pay_code') {

           /* if ($this->isPasswordResetToday()) {
                fail('每日仅可修改一次密码');
            }*/

            $key = "reset_password_".request('phone')."_".date("Ymd");
            $sms = app(Sms::class);
            if($sms->isFailCountOverSms($key)){

                 fail('每日仅可修改二次密码');
            }

            $sms->incrFailCount($key);  

		    $rules = [
			    'phone' => 'required|phone:CN,mobile',
			    'type' => 'required|string'
		    ];

	    } else {
		    fail('参数错误');
	    }

        return $rules;
    }

    public function attributes(): array
    {
	    return [
	    	'phone' => '手机号码',
		    'type' => '发送验证码类型'
	    ];
    }

    protected function isPasswordResetToday(): bool
    {
        $user = User::where('phone', request('phone'))->first();

        if (!$user) fail('无效用户');

        if ($user->password_reset_sms_at
            and $user->password_reset_sms_at->isCurrentDay()) {
            return true;
        }

        return false;
    }
}
